import { ColorPicker, type ColorPickerProps } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import { defineComponent, nextTick, onMounted, reactive } from 'vue'
import type { PropType } from 'vue'
import type { JsonSchema, Slots } from '../types'
import { ref } from 'vue'
import { getProp, trimAll } from '@/components/cms/utils'
import { formState } from '../mixins/useState'
interface IColorState {
  r: number
  g: number
  b: number
  alpha: number
  hex: string
}
export default defineComponent({
  inheritAttrs: true,
  emits: ['valueChange'],
  props: {
    schema: {
      type: Object as PropType<JsonSchema>,
      default: () => ({})
    },
    slots: {
      type: Object as PropType<Slots>,
      default: () => null
    }
  },
  setup(props, ctx) {
    const show = ref(false)
    const gradientColor = 'linear-gradient(0deg, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%)'
    const color = ref<string>('')
    const _props: ColorPickerProps = reactive({
      lang: 'ZH-cn',
      disableAlpha: false,
      disableHistory: true,
      pickerType: 'chrome',
      format: 'rgb',
      pureColor: 'rgba(0,0,0,1)',
      gradientColor
    })

    const colorState = reactive<IColorState>({ r: 0, g: 0, b: 0, alpha: 1, hex: '000000' })

    const handleRgbaSplit = (c: string) => {
      if (!c) return
      try {
        const rgbaAttr = c.match(/[\d.]+/g)
        if (rgbaAttr && rgbaAttr.length >= 3) {
          const data = rgbaAttr as unknown as number[]
          colorState.r = data[0]
          colorState.g = data[1]
          colorState.b = data[2]
          colorState.alpha = data[3] ?? '1'
          colorState.hex = data
            .slice(0, 3)
            .map((n) => {
              const res = Number(n).toString(16).toUpperCase()
              return res.length === 1 ? `0${res}` : res
            })
            .join('')
        }
      } catch (_) {
        //
      }
    }

    const handleEmit = (v: string) => {
      const value = {
        path: props.schema.field,
        value: v
      }
      ctx.emit('valueChange', value)
    }
    const handleColorChange = (v: string) => {
      color.value = v
      handleRgbaSplit(v)
      const colorValue = getProp(formState.model, props.schema.field as string).value as string
      if (!props.schema.field) {
        console.warn('字段没有传递')
        return
      } else if (!colorValue || !trimAll(colorValue)) {
        console.warn(`字段'${props.schema.field} '未设置默认值`)
      }
      console.log({ colorValue, v })
      if (trimAll(colorValue) === trimAll(v)) {
        return
      }
      handleEmit(trimAll(v))
    }
    onMounted(() => {
      nextTick(() => {
        const colorValue = getProp(formState.model, props.schema.field as string).value as string
        if (formState.model && colorValue) {
          _props.pureColor = colorValue
          // handleRgbaSplit(colorValue)
        }
        show.value = true
      })
    })
    return () =>
      show.value ? (
        <div class="color-picker__wrapper">
          {/* <span class="color-picker__label">{color.value}</span> */}
          <ColorPicker {..._props} onPureColorChange={(v) => handleColorChange(v)} />
          <div class="custom-bar flex justify-between items-center gap-x-2">
            <div class="text-center ">
              <div class="color-picker-current-color" style={{ 'background-color': `#${colorState.hex}` }}></div>
            </div>
            <div class="text-center">
              <div class="color-picker-current-hex pr-3">{colorState.hex}</div>
            </div>
            <div class="text-center">
              <div class="color-picker-current-alpha">{colorState.alpha * 100}</div>
            </div>
          </div>
          <div class="custom-bar custom-bar__text flex flex-row items-center gap-x-2">
            <div class="color-picker-current-color text-[10px]">颜色</div>
            <div class="color-picker-current-hex text-[10px]">Hex</div>
            <div class="color-picker-current-alpha text-[10px]">不透明度</div>
          </div>
        </div>
      ) : (
        <i></i>
      )
  }
})
